using System;
using UnityEngine;
using Object = UnityEngine.Object;

namespace M0
{
    public class BaseSingleMono<T> : MonoBehaviour where T : MonoBehaviour
    {
        private static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    尝试提前加载();
                }

                return _instance;
            }
        }

        private static void 尝试提前加载()
        {
            var find = GameObject.FindObjectOfType<T>();
            if (find != null)
            {
                _instance = find;
                return;
            }

            var nodestroy = GameObject.FindObjectOfType<CompNoDestory>();
            if (nodestroy == null)
            {
                nodestroy = new GameObject("永不删除", typeof(CompNoDestory)).GetComponent<CompNoDestory>();
            }

            var c = new GameObject(typeof(T).Name, typeof(T));
            c.transform.SetParent(nodestroy.transform, false);
            _instance = c.GetComponent<T>();
        }

        public virtual void F提前加载数据()
        {

        }

        private void Awake()
        {
            if (_instance == null)
            {
                BDebug.Log($"Mono单例初始化{this.GetType()}");
                AwakeInit();
            }
            else
            {
                Object.Destroy(this.gameObject);                
            }
        }


        protected virtual void AwakeInit()
        {
            if (_instance == null)
            {
                _instance = gameObject.GetComponent<T>();
            }
            else if (_instance.gameObject != gameObject)
            {
                GameObject.Destroy(gameObject);
            }
        }

        private int 执行顺序;

        private void Update()
        {
            if (执行顺序 == 0)
            {
                Start_1();
                执行顺序++;
            }

            UpdateFunc();
        }

        protected virtual void Start_1()
        {
            
        }
        protected virtual void UpdateFunc()
        {
            
        }
    }

}